﻿namespace GreenIsomer.Data.Entities.Ddl {
	using System;
	using System.IO;
	using System.Collections.Generic;

	public class Generator {

		internal const string SsdlNamespace = "http://schemas.microsoft.com/ado/2006/04/edm/ssdl";
		internal const string SsdlStoreNamespace = "http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator";
		internal const string GidexNamespace = "http://greenisomer.com/schema/data/entities/transform/settings/1.0/";

		public static string ResolvePath(string baseDirectory, string path) {
			if(string.IsNullOrEmpty(path)) return path;

			if(path.StartsWith(".", StringComparison.Ordinal))
				path = Path.Combine(baseDirectory, path);
			return Path.GetFullPath(path);
		}

		private Settings settings;
		private string baseDirectory;

		public Generator(Settings settings) : this(settings, null) { }

		public Generator(Settings settings, string baseDirectory) {
			if(settings == null) throw new ArgumentNullException("settings");

			this.settings = settings;

			if(string.IsNullOrEmpty(baseDirectory)) 
				this.baseDirectory = Environment.CurrentDirectory;
			else
				this.baseDirectory = baseDirectory;
		}

		public virtual Settings Settings {
			get { return settings; }
		}

		public virtual string BaseDirectory {
			get { return baseDirectory; }
			set { baseDirectory = value; }
		}

		public TextWriter Output { get; set; }

		public void Generate() {

			foreach(ScriptGenerator generator in settings.ScriptGenerators) {

				if(generator == null || string.IsNullOrEmpty(generator.ScriptOutputFile))
					throw new InvalidOperationException("Script output file not specified.");

				if(Output != null) {
					string path = ResolvePath(baseDirectory, generator.ScriptOutputFile);
					Output.WriteLine("  Generating " + path);
				}

				generator.Generate(baseDirectory, settings.ExtendedDefinition, settings.ProviderSettings);
			}

		}

	}

}